/**
 * 
 */
package any.desktop.server.resource;

import java.io.IOException;

import javax.activation.FileTypeMap;

import org.apache.commons.lang.StringUtils;
import org.restlet.Context;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.Variant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import any.desktop.server.DesktopService;
import any.restlet.helper.RepresentationHelper;
import any.restlet.helper.RepresentationHelperUtil;

/**
 * @author keke<keke@codehaus.org>
 * @revision $Revision: 82 $
 * @version 0.0.1
 */
public class SearchResultResource extends Resource {
    private static final Logger  LOG       = LoggerFactory
                                                   .getLogger(SearchResultResource.class);
    private static final String  QUERY_KEY = "q";
    private static final String  START_KEY = "s";
    private static final String  TYPE_KEY  = "type";
    private DesktopService       desktopService;
    private int                  length    = 10;
    private String               query;
    private RepresentationHelper repHelper;
    private int                  start;
    private String               type;

    @Override
    public void init(final Context context, final Request request,
            final Response response) {
        super.init(context, request, response);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Accepted MediaTypes: {}", request.getClientInfo()
                    .getAcceptedMediaTypes());
        }
        final Form form = request.getResourceRef().getQueryAsForm(
                request.getEntity().getCharacterSet());
        query = Reference.decode(form.getFirstValue(QUERY_KEY));
        setAvailable(!StringUtils.isEmpty(query));
        type = form.getFirstValue(TYPE_KEY);
        if (StringUtils.isEmpty(type)) {
            type = "html";
        }
        final String startStr = form.getFirstValue(START_KEY);
        if (StringUtils.isEmpty(startStr)) {
            start = 0;
        } else {
            try {
                start = Integer.valueOf(startStr);
            } catch (final NumberFormatException e) {
                if (LOG.isInfoEnabled()) {
                    LOG.info("Invalid Start value {}", startStr);
                }
                start = 0;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("To search {}, starting from {}, returning type is {}",
                    new Object[] { query, start, type });
        }
        getVariants().add(
                new Variant(MediaType
                        .valueOf(FileTypeMap.getDefaultFileTypeMap()
                                .getContentType("this." + type))));
    }

    @Override
    public Representation represent(final Variant variant)
            throws ResourceException {
        try {
            return RepresentationHelperUtil.represent(desktopService.search(
                    query, start, length), variant, "search", repHelper,
                    getResponse());
        } catch (final IOException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unable to do search [" + query + "]", e);
            }
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,
                    e.getMessage());
            return null;
        }
    }

    /**
     * Default length of each page.
     * 
     * @param length
     */
    public void setDefaultLength(final int length) {
        this.length = length;
    }

    public void setDesktopService(final DesktopService desktopService) {
        this.desktopService = desktopService;
    }

    public void setRepHelper(final RepresentationHelper repHelper) {
        this.repHelper = repHelper;
    }

}
